<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_Standard_Techan
{
    private static $_typeid = 118;

    /**
     * @desc 景点列表
     * @param $params
     * @return array
     */
    public static function search($params, $keyword, $currentpage, $pagesize = '10')
    {
        $destPy = $params['destpy'];
        $sortType = intval($params['sorttype']);
        $attrId = $params['attrid'];
        $page = $currentpage;
        $page = $page ? $page : 1;


        $where = ' WHERE a.ishidden=0 ';
        $value_arr = array();
        //按目的地搜索
        if ($destPy && $destPy != 'all')
        {
            $destId = DB::select('id')->from('destinations')->where('pinyin', '=', $destPy)->execute()->get('id');
            $where .= " AND FIND_IN_SET('$destId',a.kindlist) ";
        }

        //排序
        $orderBy = "";
        if (!empty($sortType))
        {
            if ($sortType == 1)//价格升序
            {
                $orderBy = "  a.price ASC,";
            }
            else if ($sortType == 2) //价格降序
            {
                $orderBy = "  a.price DESC,";
            }
            else if ($sortType == 3) //销量降序
            {
                $orderBy = " sellnum DESC,";
            }
            else if ($sortType == 4)//推荐
            {
                $orderBy = " a.shownum DESC,";
            }
        }


        //关键词
        if (!empty($keyword))
        {
            $where .= " AND a.title like :keyword ";
            $value_arr[':keyword'] = '%' . $keyword . '%';
        }
        //按属性
        if (!empty($attrId))
        {
            $where .= Product::get_attr_where($attrId);
        }

        $offset = (intval($page) - 1) * $pagesize;
        //查询真实购买量
        $sell_where = " LEFT JOIN (SELECT COUNT(*) as s_num,productautoid FROM `sline_member_order` WHERE typeid=118 GROUP BY productautoid) AS s ON s.productautoid=a.id";
        $files = ",(IFNULL(a.bookcount,0)+IFNULL(s.s_num,0)) AS sellnum";
        //如果选择了目的地
        if (!empty($destId))
        {
            $sql = "SELECT a.*{$files} FROM `sline_techan` a ";
            $sql .= "LEFT JOIN `sline_kindorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=118 AND a.webid=b.webid AND b.classid=$destId)";
            $sql .= $sell_where;
            $sql .= $where;
            $sql .= "ORDER BY {$orderBy} IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC ";
            //$sql.= "LIMIT {$offset},{$pagesize}";

        }
        else
        {
            $sql = "SELECT a.*{$files} FROM `sline_techan` a ";
            $sql .= "LEFT JOIN `sline_allorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=118 AND a.webid=b.webid)";
            $sql .= $sell_where;
            $sql .= $where;
            $sql .= "ORDER BY {$orderBy} IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC ";
            //$sql.= "LIMIT {$offset},{$pagesize}";


        }


        //计算总数
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by


        $totalN = DB::query(1, $totalSql)->parameters($value_arr)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? $totalN[0]['dd'] : 0;

        $sql .= "LIMIT {$offset},{$pagesize}";



        $arr = DB::query(1, $sql)->parameters($value_arr)->execute()->as_array();

        foreach ($arr as &$v)
        {
            $v['commentnum'] = Model_Comment::get_comment_num($v['id'], 118); //评论次数
            //$v['sellnum'] = Model_Member_Order::get_sell_num($v['id'], 118)+intval($v['bookcount']); //销售数量
            $v['score'] = $v['satisfyscore'] . '%';
            $v['price'] = Model_Techan::get_minprice($v['id'], $v);//最低价
            $v['attrlist'] = Model_Techan_Attr::get_attr_list($v['attrid'], 118);//属性列表.
            $v['url'] = Common::get_web_url($v['webid']) . "/techan/show_{$v['aid']}.html";
            $v['iconlist'] = Product::get_ico_list($v['iconlist']);
            if (Model_Supplier::display_is_open() && $v['supplierlist'])
            {
                $v['suppliername'] = Arr::get(Model_Supplier::get_supplier_info($v['supplierlist'], array('suppliername')), 'suppliername');
            }
            //积分抵现所需积分
            if($v['jifentprice_id'])
            {
                $jifentprice_info = Model_Jifen_Price::get_used_jifentprice($v['jifentprice_id'], 118);
                if($jifentprice_info['jifentprice'])
                {
                    $v['jifentprice'] = $jifentprice_info['jifentprice'];
                }
            }

            $v['litpic'] = Common::img($v['litpic']);
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr,
            'is_finished'=>count($arr)<$pagesize?true:false //是否还有更多的数据
        );
        return $out;
    }

    /**
     * @desc 景点详情
     * @param $id
     * @return array
     */
    public static function detail($params)
    {
        if($params['id'])
        {
            $id = $params['id'];
            $userid = $params['userid'];

            $info = DB::select()->from('techan')->where('id', '=', $id)->execute()->current();
            //seo
            $seo_info = Product::seo($info);



            $info['seo_info'] = $seo_info;
            //产品图片
            $piclist = Product::pic_list($info['piclist']);
            $p = array();
            foreach ($piclist as &$pic)
            {
                $pi = Model_Api_Standard_System::reorganized_resource_url($pic[0]);
                array_push($p, $pi);
            }

            $info['piclist'] = $p;
            //属性列表
            $info['attrlist'] = Model_Techan::product_attr($info['attrid']);

            //点评数
            $info['commentnum'] = Model_Comment::get_comment_num($info['id'], self::$_typeid);
            //销售数量
            $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], self::$_typeid) + intval($info['bookcount']);
            //产品编号
            $info['series'] = St_Product::product_series($info['id'], self::$_typeid);
            //产品图标
            $info['iconlist'] = Product::get_ico_list($info['iconlist']);
            //行程附件
            $info['linedoc'] = unserialize($info['linedoc']);
            //满意度
            $info['score'] = St_Functions::get_satisfy(self::$_typeid, $info['id'], $info['satisfyscore']);

            $info['litpic'] = Model_Api_Standard_System::reorganized_resource_url($info['litpic']);

            $info['basehost'] = $GLOBALS['cfg_basehost'];



            //扩展字段信息
            $extend_info = Model_Techan::extend($info['id'], self::$_typeid);
            $info['extend_info'] = $extend_info;


            //套餐信息
            $info['suit_info'] = self::suit($info['id']);

            //租车详情内容
            $params = array(
                'typeid'        => self::$_typeid,
                'productinfo'   => $info,
                'onlyrealfield' => 1,
                'pc'            => 0,

            );
            $info['detail_list'] = self::get_content($params);

            // 更加ID查询可用的优惠券
            if(St_Functions::is_normal_app_install('coupon'))
            {
                $info['coupon_list'] = Model_Coupon::get_product_coupon_list($info['id'],self::$_typeid);
            }


            //分销赚取的金额
            if(St_Functions::is_normal_app_install('mobiledistribution'))
            {
                if(!empty($userid))
                {
                    $fenxiao = DB::select()->from('fenxiao')->where("memberid",'=',$userid)->execute()->current();
                    $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid",'=',$userid)->execute()->current();
                    $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$params['typeid'],$fxgroupid['fxgroupid']);
                    if($commission_type==1)
                    {
                        $commission_rate = Model_Fenxiao::get_commission_rate($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                        $v['commission'] =$commission_rate[0]*100;
                        $v['commission'] = empty($v['commission'])?0:$v['commission'];
                        $v['commission'] .='%';
                        $v['profit'] = $info['price']*$commission_rate[0];
                    }
                    else if($commission_type==2)
                    {
                        $commission_rate = Model_Fenxiao::get_commission_rate_platform($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                        $v['commission'] =$commission_rate[0]*100;
                        $v['commission'] = empty($v['commission'])?0:$v['commission'];
                        $v['commission'] .='%';
                        $temp_order = array('typeid'=>$params['typeid'],'productautoid'=>$info['id'],'totalprice'=>$info['price'],'dingnum'=>1);
                        $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                        $platform_price = $platform_price==0? $info['price']:$platform_price;
                        $v['profit'] = $platform_price*$commission_rate[0];
                    }
                    else
                    {
                        $commission_cash = Model_Fenxiao::get_commission_cash_line($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                        $v['commission'] = $commission_cash[0]['adult'];
                        $v['commission'] = empty($v['commission'])?0:$v['commission'];
                        $v['profit'] = $v['commission'];
                    }
                    $info['profit'] = $v['profit'];
                    $info['is_fenxiao'] = !empty($fenxiao) && $fenxiao['status']==1?true:false;
                }
            }
            return $info;
        } else
        {
            return array();
        }
    }
    /**
     * @desc 获取线路套餐列表
     * @param $productid
     * @return mixed
     */
    private static function suit($productid)
    {
        $pay_name = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认',
        );

        $suit = DB::select()->from('techan_suit')
            ->where('productid', '=', $productid)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();
        foreach ($suit as &$r)
        {
            $beforBook = array(
                'suitid' => $r['id'],
                'info'   => $r,
            );
            $r['price'] = Model_Techan::get_minprice($productid,array('suitid',$r['id']));
            $r['title'] = $r['suitname'];
            $r['paytype_name'] = $pay_name[$r['paytype']];
        }

        return $suit;
    }

    /**
     * @desc 获取线路详细行程内容
     * @param $params
     * @return array
     */
    private static function get_detail_content($params)
    {

        $default = array(
            'typeid'        => self::$_typeid,
            'productinfo'   => 0,
            'onlyrealfield' => 1,
            'pc'            => 0,

        );
        $params = array_merge($default, $params);
        extract($params);
        $arr = DB::select()->from('techan_content')
            ->where('webid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $ar = DB::select()->from('car_extend_field')->where('productid', '=', $productid)->execute()->as_array();

        $list = array();
        foreach ($arr as $v)
        {
            if ($v['columnname'] == 'tupian')
            {
                continue;
            }
            if ($v['isrealfield'] == 1)
            {
                $content = ! empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ? $content : '';
            }
            if (empty($content))
            {
                continue;
            }

            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];

            //$a['xcx_content'] = Model_Api_Standard_Xcx::filter_content($content); //针对小程序去除样式
            $a['content'] = Model_Api_Standard_Xcx::filter_content($content);
            $list[] = $a;

        }

        return $list;
    }

    public static function get_content($params)
    {
        $default=array(
            'typeid'=>'',
            'productinfo'=>0,
            'onlyrealfield'=>0,
            'pc'=>0

        );

        $params=array_merge($default,$params);
        extract($params);


        $table ='sline_techan_content';
        $extend_tables = 'sline_techan_extend_field';
        $where = '';

        $sql = "SELECT columnname,chinesename,isrealfield FROM {$table} ";

        $sql.= "WHERE webid=0 and isopen=1 ";

        $sql.= "ORDER BY displayorder ASC";
        $arr = DB::query(1,$sql)->execute()->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $sql = "SELECT * FROM $extend_tables WHERE productid='$productid'";
        $ar = DB::query(1,$sql)->execute()->as_array();
        $list = array();
        foreach($arr as $v)
        {
            if ($v['columnname'] == 'tupian')
            {
                continue;
            }
            $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
            $content = $content ? $content : '';

            if(empty($content)) continue;

            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];

            $a['content'] = Model_Api_Standard_Xcx::filter_content($content);
            $list[] = $a;

        }
        return $list;

    }
}